import json

import requests
from sts.sts import Sts
from django.conf import settings
from rest_framework.filters import BaseFilterBackend
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from xiaochengxu.extensions.auth import XiaoChengXuAuthentication
from xiaochengxu.extensions.time_stamp import get_time_now
from xiaochengxu import models
from xiaochengxu.serializer.sns_serializer import CreatSnsSerializers, GetSnsSerializers, CreatCommentSerializers, \
    GetCommentSerializers, GetSnsDetailSerializers
from xiaochengxu.extensions.msg_chack import Chack_msg


class CreateSns(CreateAPIView):
    queryset = models.Sns_content.objects.all()
    serializer_class = CreatSnsSerializers

    def create(self, request, *args, **kwargs):
        # 重写create方法，自定义返回字段
        super().create(request)
        return Response('保存成功')

    def perform_create(self, serializer):
        # 重写保存方法
        user = models.User_info.objects.filter(uid=self.request.user.id).first()
        openid = self.request.data.get('openid')
        type = self.request.data.get('type')
        topic_id = self.request.data.get('topic_id')
        image_list = self.request.data.get('image_list')
        content = self.request.data.get('content')

        if Chack_msg.msg_sec_check(openid=openid,content=content):
            sns_id = serializer.save(user=user, type=type, topic_id=topic_id, creat_time=get_time_now(), update_time=get_time_now())
        else:
            sns_id = serializer.save(user=user, type=type, status=0, topic_id=topic_id, creat_time=get_time_now(), update_time=get_time_now())
        # models.Sns_image.objects.create()
        for i in image_list:
            models.Sns_image.objects.create(path=i, sns=sns_id, key=333)


class Test(APIView):

    def get(self, request, *args, **kwargs):
        print(request.user)
        return Response('hhhh')


class GetSnsList(ListAPIView):
    authentication_classes = []
    queryset = models.Sns_content.objects.all().order_by('-id')
    serializer_class = GetSnsSerializers


class GetSnsDetail(RetrieveAPIView):
    authentication_classes = []
    queryset = models.Sns_content.objects
    serializer_class = GetSnsDetailSerializers


class CreateComment(CreateAPIView):
    queryset = models.Sns_comment.objects.all()
    serializer_class = CreatCommentSerializers

    def create(self, request, *args, **kwargs):
        # 重写create方法，自定义返回字段
        super().create(request)
        return Response('保存成功')

    def perform_create(self, serializer):
        # 重写保存方法，
        user = models.User_info.objects.filter(uid=self.request.user.id).first()
        sns = models.Sns_content.objects.filter(id=self.request.data.get('sns')).first()
        serializer.save(user=user, sns=sns,
                        creat_time=get_time_now(), update_time=get_time_now())


class CommentFilterBackend(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        # sns_id = request.data.get('sns', None)
        sns_id = request.GET.get('sns', None)
        if not sns_id:
            return queryset.none()
        return queryset.filter(sns_id=sns_id, depth=1)


class GetComment(ListAPIView):
    authentication_classes = []
    queryset = models.Sns_comment.objects.all()
    serializer_class = GetCommentSerializers
    filter_backends = [CommentFilterBackend]


class Credential_view(APIView):
    authentication_classes = []
    '''
    获取腾讯临时密钥   
    '''

    def get(self, request, *args, **kwargs):
        config = {
            'url': 'https://sts.tencentcloudapi.com/',
            # 域名，非必须，默认为 sts.tencentcloudapi.com
            'domain': 'sts.tencentcloudapi.com',
            # 临时密钥有效时长，单位是秒
            'duration_seconds': 1800,
            'secret_id': settings.TENCENT_SECRET_ID,
            # 固定密钥
            'secret_key': settings.TENCENT_SECRET_KEY,
            # 换成你的 bucket
            'bucket': 'lightweightbaby-1259544235',
            # 换成 bucket 所在地区
            'region': 'ap-nanjing',
            # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
            # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            'allow_prefix': '*',
            # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allow_actions': [
                # 简单上传
                # 'name/cos:PutObject',
                'name/cos:PostObject',
                # 分片上传
                # 'name/cos:InitiateMultipartUpload',
                # 'name/cos:ListMultipartUploads',
                # 'name/cos:ListParts',
                # 'name/cos:UploadPart',
                # 'name/cos:CompleteMultipartUpload'
            ],
        }

        try:
            sts = Sts(config)
            response = sts.get_credential()
            print('get data : ' + json.dumps(dict(response), indent=4))
        except Exception as e:
            print(e)
        return Response(response)
